package fr.iut2.tc4.gestionabsencesnotes.controleurservlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.torque.util.Criteria;

import fr.iut2.tc4.gestionabsencesnotes.modelebean.GestionFactory;
import fr.iut2.tc4.gestionabsencesnotes.torque.generated.Absence;
import fr.iut2.tc4.gestionabsencesnotes.torque.generated.AbsencePeer;
import fr.iut2.tc4.gestionabsencesnotes.torque.generated.Etudiant;
import fr.iut2.tc4.gestionabsencesnotes.torque.generated.EtudiantPeer;
import fr.iut2.tc4.gestionabsencesnotes.torque.generated.Groupe;
import fr.iut2.tc4.gestionabsencesnotes.torque.generated.Note;
import fr.iut2.tc4.gestionabsencesnotes.torque.generated.NotePeer;

public class Controleur extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4894518906906862991L;
	private String urlEditAbsences;
	private String urlViewAbsences;
	private String urlDeleteAbsences;
	private String urlEditAbsence;
	private String urlEditNotes;
	private String urlViewNotes;
	// INIT
		public void init() throws ServletException {
			urlEditAbsences = getServletConfig().getInitParameter("urlEditAbsences");
			urlViewAbsences = getServletConfig().getInitParameter("urlViewAbsences");
			urlDeleteAbsences = getServletConfig().getInitParameter("urlDeleteAbsences");
			urlEditAbsence = getServletConfig().getInitParameter("urlEditAbsence");
			urlEditNotes = getServletConfig().getInitParameter("urlEditNotes");
			urlViewNotes = getServletConfig().getInitParameter("urlViewNotes");
		}
		
		// POST
		public void doPost(HttpServletRequest request, HttpServletResponse response)
				throws IOException, ServletException {
			// on passe la main au GET
			doGet(request, response);
		}
		
		// GET
		public void doGet(HttpServletRequest request, HttpServletResponse response)
				throws IOException, ServletException {


			// On recupere la methode d'envoi de la requete
			String methode = request.getMethod().toLowerCase();
			
			// On recupere l'action a� executer
			String action = request.getPathInfo();
			if (action == null) {
				action = "/viewNotes";
				System.out.println("action == null");
			}
			System.out.println(action);
			
			// Execution action
			if (methode.equals("get") && action.equals("/editAbsences")) {
				try {
					doEditAbsences(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else if (methode.equals("get") && action.equals("/viewAbsences")) {
				try {
					doViewAbsences(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			} else if (methode.equals("get") && action.equals("/deleteAbsence")) {
				try {
					doDeleteAbsence(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			} else if (methode.equals("get") && action.equals("/editAbsence")) {
				try {
					doEditAbsence(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			} else if (methode.equals("get") && action.equals("/viewNotes")) {
				try {
					doViewNotes(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			} else if (methode.equals("get") && action.equals("/editNotes")) {
				try {
					doEditNotes(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			}else if (methode.equals("post") && action.equals("/editAbsences")) {
				try {
					doEditAbsences(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			}else if (methode.equals("post") && action.equals("/viewAbsences")) {
				try {
					doViewAbsences(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			} else if (methode.equals("post") && action.equals("/deleteAbsence")) {
				try {
					doDeleteAbsence(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			} else if (methode.equals("post") && action.equals("/editAbsence")) {
				try {
					doEditAbsence(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			} else if (methode.equals("post") && action.equals("/viewNotes")) {
				try {
					doViewNotes(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			} else if (methode.equals("post") && action.equals("/editNotes")) {
				try {
					doEditNotes(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			} else {
				// Autres cas
				try {
					doViewNotes(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
		//Checkbox suppression note a faire --------------------------
		@SuppressWarnings("unchecked")
		private void doEditNotes(HttpServletRequest request,
				HttpServletResponse response) throws Exception {
		
			List<Etudiant> listEtudiants = GestionFactory.getEtudiants();
			Map<String, String[]> mapRequest = request.getParameterMap();
			
			Groupe groupeChoisit = new Groupe();
			groupeChoisit.setNomGroupe(request.getParameter("groupe"));
			List<Groupe> listGroupe = new ArrayList<Groupe>();
			listGroupe = GestionFactory.getGroupeList();
			
			if(mapRequest != null){
				GestionFactory.saveNoteFromRequest(mapRequest);
				if(request.getParameter("createNote") != null){
					GestionFactory.saveNewNoteFromRequest(mapRequest);
				}
			}
			//Traitement filtre par groupe
			if(groupeChoisit.getNomGroupe() != null && !groupeChoisit.getNomGroupe().equals("Tous")){
				listEtudiants = GestionFactory.getEtudiantsParGroupe(groupeChoisit.getNomGroupe());
				
			}else{
				groupeChoisit.setNomGroupe("Tous");
				 listEtudiants = GestionFactory.getEtudiants();
			}
			request.setAttribute("groupeChoisit", groupeChoisit);
			request.setAttribute("triEtudiantChoisit", "Aucun");
			request.setAttribute("listGroupe", listGroupe);
			request.getSession().setAttribute("listEtudiants", listEtudiants);
			if(request.getParameter("createNote") != null || request.getParameter("editNote") != null){
				loadJSP(urlViewNotes, request, response);
			}else{
				loadJSP(urlEditNotes, request, response);
			}
			
		}

		@SuppressWarnings("unchecked")
		private void doViewNotes(HttpServletRequest request,
				HttpServletResponse response) throws Exception {
			
			List<Etudiant> listEtudiants;
			Groupe groupeChoisit = new Groupe();
			groupeChoisit.setNomGroupe(request.getParameter("groupe"));
			List<Groupe> listGroupe = new ArrayList<Groupe>();
			listGroupe = GestionFactory.getGroupeList();
			if(groupeChoisit.getNomGroupe() != null && !groupeChoisit.getNomGroupe().equals("Tous")){
				listEtudiants = GestionFactory.getEtudiantsParGroupe(groupeChoisit.getNomGroupe());				
			}else{
				groupeChoisit.setNomGroupe("Tous");
				listEtudiants = GestionFactory.getEtudiants();
			}
			/*** Tri Etudiant ***/
			String triEtudiant = ""+request.getParameter("triEtudiant");
			if(triEtudiant.equals("croissant") && triEtudiant != null){
				Collections.sort(listEtudiants);
			}else if(triEtudiant.equals("decroissant") && triEtudiant != null){
				Collections.sort(listEtudiants);
				Collections.sort(listEtudiants, Collections.reverseOrder());
			}else{
				triEtudiant = "Aucun";
			}
			
			/*** Tri Note ***/
			/*
			String triNote = ""+request.getParameter("triNote");
			System.out.println("trie"+triNote);
			if(triNote.equals("croissant") && triNote != null){
				Collections.sort(listGroupe);
				System.out.println("Trie croissant: "+triNote.toString());
			}else if(triNote.equals("decroissant") && triNote != null){
				Collections.sort(listGroupe);
				Collections.sort(listGroupe, Collections.reverseOrder());
				System.out.println("trie decroissant: "+listEtudiants.toString());
			}else{
				triEtudiant = "Aucun";
			}
			*/
			request.setAttribute("triEtudiantChoisit", triEtudiant);
			//request.setAttribute("triNoteChoisit", "ezrzer");
			request.setAttribute("groupeChoisit", groupeChoisit);
			request.setAttribute("listGroupe", listGroupe);
			request.getSession().setAttribute("listEtudiants", listEtudiants);
			loadJSP(urlViewNotes, request, response);
			
		}

		private void doViewAbsences(HttpServletRequest request,
				HttpServletResponse response) throws Exception {

			List<Groupe> listGroupe = new ArrayList<Groupe>();
			listGroupe = GestionFactory.getGroupeList();
			List<Etudiant> listEtudiants = GestionFactory.getEtudiants();
			String groupeChoisit = request.getParameter("groupe");
			
			if(groupeChoisit != null && !groupeChoisit.equals("Tous")){
				listEtudiants = GestionFactory.getEtudiantsParGroupe(groupeChoisit);
				
			}else{
				groupeChoisit = "Tous";
				listEtudiants = GestionFactory.getEtudiants();
			}
			
			request.setAttribute("groupeChoisit", groupeChoisit);
			request.setAttribute("listGroupe", listGroupe);
			request.getSession().setAttribute("listEtudiants", listEtudiants);
			loadJSP(urlViewAbsences, request, response);
			
		}

		private void doEditAbsences(HttpServletRequest request,
				HttpServletResponse response) throws Exception {

			// On recupere la methode d'envoi de la requete
			/*String methode = request.getMethod().toLowerCase();
			List<Groupe> listGroupe = new ArrayList<Groupe>();
			listGroupe = GestionFactory.getGroupeList();
			List<Etudiant> listEtudiants = GestionFactory.getEtudiants();
			String groupeChoisit = "";
			
			// On récupère le groupe choisit en fonction de la requête
			if(methode.equals("post")) {
				groupeChoisit = request.getParameter("groupForm");
			}
			else {
				groupeChoisit = request.getParameter("groupe");
			}
			
			// On construit la liste d'étudiants en fonction de groupeChoisit
			if(groupeChoisit != null && !groupeChoisit.equals("Tous")){
				listEtudiants = GestionFactory.getEtudiantsParGroupe(groupeChoisit);
				
			}else{
				groupeChoisit = "Tous";
				listEtudiants = GestionFactory.getEtudiants();
			}
			request.setAttribute("groupeChoisit", groupeChoisit);
			
			// Si requête = post, on enregistre les modifications et redirige vers viewAbsences
			if(methode.equals("post")) {
				Map<String, String[]> mapRequest = request.getParameterMap();
				if(mapRequest != null) {
					HashMap<Integer, Integer> listAbsences = new HashMap<Integer, Integer>();
					for(Entry<String, String[]> entry : mapRequest.entrySet()){
						//If pour ignorer le parametre 'groupe' dans la map de requete.
						if(!entry.getKey().equals("groupForm")){
							int idEtudiant = Integer.parseInt(entry.getKey());
							int absences =  Integer.parseInt(entry.getValue()[0]);
							GestionFactory.setAbsences(idEtudiant, absences);
						}
					}
				}
				/*int length = listEtudiants.size();
				System.out.print(length);
				for(int i=0; i<length; i++) {
					absences = request.getParameter(Integer.toString(i));
					//GestionFactory.setAbsences(i, Integer.parseInt(absences));
				}
				doViewAbsences(request, response);
			}
			// Sinon, on affiche le formulaire de modification d'absences
			else {
				request.setAttribute("listGroupe", listGroupe);
				request.getSession().setAttribute("listEtudiants", listEtudiants);
				loadJSP(urlEditAbsences, request, response);
			}*/
			
			String methode = request.getMethod().toLowerCase();
			
			if(methode.equals("post")) {
				Absence absence = new Absence();
				String dateAbs = "";
				dateAbs += request.getParameter("jour");
				dateAbs += " ";
				dateAbs += request.getParameter("mois");
				dateAbs += " ";
				dateAbs += request.getParameter("annee");
				absence.setIdEtudiant(Integer.parseInt(request.getParameter("idEtudiant")));
				absence.setDateAbsence(dateAbs);
				absence.save();
				doViewAbsences(request, response);
			}
			else {
				Etudiant etudiant = EtudiantPeer.retrieveByPK(Integer.parseInt(request.getParameter("etu")));
				List<Absence> listAbsences = new ArrayList<Absence>();
				listAbsences = etudiant.getAbsences();
				request.setAttribute("etudiant", etudiant);
				request.setAttribute("listAbsences", listAbsences);
				loadJSP(urlEditAbsences, request, response);
			}
		}
		
		private void doDeleteAbsence(HttpServletRequest request,
				HttpServletResponse response) throws Exception {
			
			String methode = request.getMethod().toLowerCase();
			
			if(methode.equals("post")) {
				Absence absence = AbsencePeer.retrieveByPK(Integer.parseInt(request.getParameter("idAbs")));
				AbsencePeer.doDelete(absence);
				doViewAbsences(request, response);
			}
			else {
				Absence absence = AbsencePeer.retrieveByPK(Integer.parseInt(request.getParameter("idAbs")));
				Etudiant etudiant = EtudiantPeer.retrieveByPK(absence.getIdEtudiant());
				request.setAttribute("absence", absence);
				request.setAttribute("etudiant", etudiant);
				loadJSP(urlDeleteAbsences, request, response);
			}
		}
		
		private void doEditAbsence(HttpServletRequest request,
				HttpServletResponse response) throws Exception {
			
			String methode = request.getMethod().toLowerCase();
			
			if(methode.equals("post")) {
				Absence absence = AbsencePeer.retrieveByPK(Integer.parseInt(request.getParameter("idAbs")));
				String dateAbs = "";
				dateAbs += request.getParameter("jour");
				dateAbs += " ";
				dateAbs += request.getParameter("mois");
				dateAbs += " ";
				dateAbs += request.getParameter("annee");
				absence.setDateAbsence(dateAbs);
				AbsencePeer.doUpdate(absence);
				doViewAbsences(request, response);
			}
			else {
				Absence absence = AbsencePeer.retrieveByPK(Integer.parseInt(request.getParameter("idAbs")));
				Etudiant etudiant = EtudiantPeer.retrieveByPK(absence.getIdEtudiant());
				request.setAttribute("absence", absence);
				request.setAttribute("etudiant", etudiant);
				loadJSP(urlEditAbsence, request, response);
			}
		}
		
		public void loadJSP(String url, HttpServletRequest request,
				HttpServletResponse response) throws ServletException, IOException {
			
			ServletContext sc = getServletContext();
			RequestDispatcher rd = sc.getRequestDispatcher(url);
			rd.forward(request, response);
		}
}
